package com.liust.myproject_client.Service;

import com.liust.myproject.Pojo.PayPojo;
import com.liust.myproject_client.Dao.payRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author liuyulong
 * @create 2022-03-17 12:19
 * @create 2022-三月  星期四
 * @project MyProject_Client
 */
@Service
public class payService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private payRepository payRepository;

    /**
     * 支付(存钱)功能
     * 0为存钱
     * 1为扣钱
     * @param payPojo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String toPayTransactional(PayPojo payPojo){
        int insert = payRepository.insert(payPojo);
        return String.valueOf(payPojo.getPayId());
    }

    /**
     * 扣钱和加钱方的sql生效
     * (通过将is_mq=1修改成 转账者id)
     * @param transferId
     * @param payPojo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void toUpdateTransfer(String transferId,PayPojo payPojo) {

        //接收者加钱
        int insert = payRepository.insert(payPojo);

        PayPojo transfer = payRepository.selectById(transferId);
        PayPojo receiver = payRepository.selectById(payPojo.getPayId());
        transfer.setIsMq(Integer.valueOf(transfer.getUserId()));
        receiver.setIsMq(Integer.valueOf(transfer.getUserId()));

        int transferUpdate = payRepository.updateById(transfer);
        int receiverUpdate = payRepository.updateById(receiver);

//        保证上面全部操作完成
        if((transferUpdate+receiverUpdate+insert)!=3){
            logger.error("接收者加钱操作: " + transferId);
            logger.error("确认 转账者扣钱: " + receiverUpdate);
            logger.error("确认 接收者加钱: " + insert);
            logger.error("发送方用户:"+transfer.getUserId()+" 接收方用户:"+receiver.getUserId()+" 转账失败");
            throw new RuntimeException("无法修改转出方和接收方(修改错误)");
        }
    }

}
